/*
 * UserAddressManager.java
 * business
 *
 * Created by ChenTao on 2016/9/9.
 *
 * Copyright (c) 2016年 yidiandao. All rights reserved.
 */

package com.yidiandao.business.manager;

import com.yidiandao.business.data.bean.UserAddress;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户地址 Manager
 */
public class UserAddressManager {

    private static UserAddressManager manager;

    private List<UserAddress> mUserAddressList = new ArrayList<>();

    private UserAddress savedUserAddress;

    private UserAddressManager() {
    }

    public static UserAddressManager getInstance() {
        if (manager == null) {
            synchronized (UserAddressManager.class) {
                if (manager == null) {
                    manager = new UserAddressManager();
                }
            }
        }
        return manager;
    }

    /**
     * 初始化用户地址列表.会在 进入编辑地址列表与选择地址列表时 初始化数据
     */
    public void initAddressList(List<UserAddress> userAddresses) {
        mUserAddressList.clear();
        mUserAddressList.addAll(userAddresses);
    }

    /**
     * 选中地址列表中的一个地址
     *
     * @param userAddress 被选中的地址
     */
    public void selectAddress(UserAddress userAddress) {
        for (UserAddress address : mUserAddressList) {
            address.setSelected(address.equals(userAddress));
        }

        saveSelectedAddress(userAddress);
    }

    /**
     * 设置地址列表中的一个为默认地址
     *
     * @param userAddress 被选中的地址
     */
    public void setDefaultAddress(UserAddress userAddress) {
        for (UserAddress address : mUserAddressList) {
            address.setDefault(address.equals(userAddress));
        }
    }

    /**
     * 获取地址操作列表选择的地址
     */
    public UserAddress getSelectedAddress() {

        int position = -1;

        for (int i = 0; i < mUserAddressList.size(); i++) {
            if (mUserAddressList.get(i).isSelected()) {
                position = i;
                break;
            }
        }

        if (position == -1) {
            return null;
        }

        return mUserAddressList.get(position);
    }

    /**
     * 为避免再次进入选择地址列表时，选中的地址与确认订单页面的地址不一致.将用户上一次选择的地址保存
     */
    private void saveSelectedAddress(UserAddress userAddress) {
        savedUserAddress = userAddress;
    }

    /**
     * 获取上一次选中的地址
     */
    public UserAddress getSavedSelectedUserAddress() {
        return savedUserAddress;
    }

    public void clearSavedUserAddress() {
        savedUserAddress = null;
    }
}
